package com.adminx.dao;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.adminx.entity.Code;
import com.adminx.pojo.CodePojo;
import com.adminx.util.PageResults;

@Repository
public class CodeDao extends BaseDao<Code, Long>{
	
	protected static Logger LOGGER = Logger.getLogger(CodeDao.class); 
	
	/**
	 * 分页查找
	 */
	public PageResults<CodePojo> queryValueCode(Integer pageIndex, Integer pageSize, String searchText){
		String sql = 
			"SELECT " +
			"	t.code_id id, " +
			"	t.code_name codeName, " +
			"	DATE_FORMAT( " +
			"		t.create_date, " +
			"		'%Y-%m-%d %H:%i:%S' " +
			"	) createDate, " +
			"	DATE_FORMAT( " +
			"		t.update_date, " +
			"		'%Y-%m-%d %H:%i:%S' " +
			"	) updateDate, " +
			"	t.status_code statusCode " +
			"FROM " +
			"	xx_code t";
		
		String countSql = 
			"SELECT count(1) " +
			"FROM " +
			"	xx_code t";
		
		if(!StringUtils.isBlank(searchText)){
			sql += " WHERE t.code_name like '%" + searchText + "%' or t.remark like '%" + searchText + "%' ";
			countSql += " WHERE t.code_name like '%" + searchText + "%' or t.remark like '%" + searchText + "%' ";
		}	
		
		return this.findPageByFetchedSql(CodePojo.class, sql, countSql, pageIndex, pageSize);
	}
	
	/**
	 * 分页查找子集
	 */
	public PageResults<CodePojo> queryValueDetail(Integer pageIndex, Integer pageSize, Long codeId){
		String sql = 
			"SELECT " +
			"	t.code_id id, " +
			"	t.code_name codeName, " +
			"	DATE_FORMAT( " +
			"		t.create_date, " +
			"		'%Y-%m-%d %H:%i:%S' " +
			"	) createDate, " +
			"	DATE_FORMAT( " +
			"		t.update_date, " +
			"		'%Y-%m-%d %H:%i:%S' " +
			"	) updateDate, " +
			"	t.status_code statusCode " +
			"FROM " +
			"	xx_code t where t.parent_id = "+ codeId;
		
		String countSql = 
			"SELECT count(1) " +
			"FROM " +
			"	xx_code t where t.parent_id = "+ codeId;
		return this.findPageByFetchedSql(CodePojo.class, sql, countSql, pageIndex, pageSize);
	}
	
	/**
	 * 批量删除
	 * @param authorityId
	 */
	public int delBatch(String ids) {
		
		String[] idsArray = ids.split(",");
		String hql = "";
		for (int i = 0; i < idsArray.length; i++) {
			if (i == 0) {
				hql = "codeId=" + idsArray[i];
			} else {
				hql = hql + " or codeId=" + idsArray[i];
			}
		}
		int updateCount = this.getSession().createQuery("DELETE FROM Code WHERE " + hql).executeUpdate();
		return updateCount;
	}
	
	/**
	 * 禁用
	 */
	public void ban(Long id){
		String sql = "update xx_code c set c.status_code = case c.status_code when 0 then 1 when 1 then 0 else 1 end where c.code_id =  "+id;
		this.getSession().createSQLQuery(sql).executeUpdate();
	}
}
